package server

import (
	"encoding/json"
	"fmt"
	"gin/dao"
	"gin/model"
	"gin/param"
	"gin/tool"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"math/rand"
	"time"
)

type MemberServer struct {
}

func (ms *MemberServer) SendCode(mobile string, status int) (bool, string) {
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	var config = tool.GetConfig().Sms
	client, _ := dysmsapi.NewClientWithAccessKey(config.RegionId, config.AppKey, config.AppSecret)
	request := dysmsapi.CreateSendSmsRequest()
	par, _ := json.Marshal(map[string]interface{}{
		"code": code,
	})
	request.Scheme = "https"
	request.SignName = config.SignName
	request.PhoneNumbers = mobile
	request.TemplateCode = config.TemplateCode
	request.TemplateParam = string(par)
	response, err := client.SendSms(request)
	if err != nil {
		fmt.Print(err.Error())
		return false, response.Message
	}
	if response.Code != "OK" {
		return false, response.Message
	}
	SmsCode := model.SmsCode{
		Mobile: mobile,
		Code:   code,
		BizId:  response.BizId,
		Status: status,
		Ctime:  time.Now().Unix(),
	}
	MemberDao := dao.MemberDao{Orm: tool.DbEngine}
	result := MemberDao.InsertCode(SmsCode)
	if result > 0 {
		return true, "短信发送成功"
	} else {
		return false, "数据插入失败"
	}
}

//用户注册
func (ms *MemberServer) Register(param param.RegisterParam) (bool, string, *model.Member) {
	MemberDao := dao.MemberDao{Orm: tool.DbEngine}
	ValMobileCode := MemberDao.ValidateSmsCode(param.Mobile, param.Code, 1)
	if ValMobileCode.Id == 0 {
		return false, "验证码验证失败", nil
	}
	//expireTime := time.Now().Unix() - ValMobileCode.Ctime
	//if expireTime > 180{
	//	return false,"验证码过期",nil
	//}
	//插入数据到 member 表
	memberInfo := model.Member{}
	memberInfo.Account = param.Account
	memberInfo.Password = param.Password
	memberInfo.Mobile = param.Mobile
	memberInfo.Nickname = param.Nickname
	memberInfo.Balance = "0.00"
	memberInfo.Ctime = time.Now().Unix()
	memberInfo.Utime = time.Now().Unix()
	affected := MemberDao.MemberRegister(memberInfo)
	if affected > 0 {
		memberInfo.Password = ""
		return true, "用户注册成功", &memberInfo
	}
	return false, "用户注册失败", nil
}

//用户登录
func (ms *MemberServer) AccPassLogin(param param.AccPassLoginParam) *model.Member {
	MemberDao := dao.MemberDao{Orm: tool.DbEngine}
	AccPassLogin := MemberDao.AccPassLogin(param)
	//fmt.Println(AccPassLogin.Id)
	return AccPassLogin
}

//手机号 验证码登录
func (ms *MemberServer) SmsLogin(param param.SmsLoginParam) (*model.Member, string) {
	MemberDao := dao.MemberDao{Orm: tool.DbEngine}
	MobileIsSet := MemberDao.MobileIsSet(param)
	ValidateSmsCode := MemberDao.ValidateSmsCode(param.Mobile, param.Code, 2)
	if len(MobileIsSet.Mobile) <= 0 {
		//fmt.Println("-----------------iiiiiiiiiiiiiiiiii---------------------")
		return nil, "手机号不正确"
	}
	if len(ValidateSmsCode.Mobile) <= 0 {
		//fmt.Println("------------sssssssssssssssssss----------------")
		return nil, "验证码不正确"
	}
	return MobileIsSet, "SUCCESS"
}
